package com.example.messagedigest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MainActivity extends AppCompatActivity {
private String pw="softpo123";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
//button点击事件，进行运算
    public void messageDigest(View view) {
         switch (view.getId()){

             case R.id.md5: //32位的
                 String md5 = messageDiagest("MD5", pw);
                 Log.d("flag", "-----------messageDigest: "+md5);
                 break;
             case R.id.sha1://40位
               String sha1=messageDiagest("SHA-1",pw);
                 break;
         }
    }

    //运算方法
    private String messageDiagest(String type, String data) {
    //1创建消息摘要的对象
        StringBuilder sb=null;
        try {
            MessageDigest messageDigest=MessageDigest.getInstance(type);

            //2调用对象的方法，进行运算

            //将要运算的数据加载给messagedigest
            messageDigest.update(data.getBytes());

            byte[] digest = messageDigest.digest();

             //3将字节数组装换成该样式

            //3.1打印字节数组
            Log.d("flag", "-----------hash值的长度 --messageDiagest: "+digest.length);
            for (int i = 0; i < digest.length; i++) {
                Log.d("flag", "------------messageDiagest: "+digest[i]);
            }

             sb=new StringBuilder();
            for (int i = 0; i < digest.length; i++) {
                int num = digest[i] & 0xFF;

                if (num<=0xF){
                    sb.append(0);
                }
                String string = Integer.toHexString(num);
                sb.append(string);

            }

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return sb.toString();


    }
}
